<template>
  <div class="pad-20 bgc-default">
    <div class="flex v-align-c tab-wx-type pad-b-20">
      <el-button v-if="getVersionType() != 5 && enterpriseConfig.shopSelectionAuthority !== 1" class="mar-r-10"
        :class="appType === 10 ? 'active' : ''" @click="changeAppType(10)">
        <div class="flex v-align-c">
          <img src="https://veekrayimg.joinsun.vip/images/logo-veekray.png" class="width-60 height-60 mar-r-18" />
          <span>云店小程序</span>
        </div>
      </el-button>
      <el-button v-if="getVersionType() == 5 && enterpriseConfig.shopSelectionAuthority !== 1" class="mar-r-10"
        :class="appType === 12 ? 'active' : ''" @click="changeAppType(12)">
        <div class="flex v-align-c">
          <img src="https://veekrayimg.joinsun.vip/images/logo-veekray.png" class="width-60 height-60 mar-r-18" />
          <span>社区小程序</span>
        </div>
      </el-button>
      <el-button v-if="getVersionType() != 5 && enterpriseConfig.wholesaleAuthority == 1"
        :class="appType === 11 ? 'active' : ''" @click="changeAppType(11)">
        <div class="flex v-align-c">
          <img src="https://veekrayimg.joinsun.vip/upload/pifa.png" class="width-60 height-60 mar-r-18" />
          <span>批发小程序</span>
        </div>
      </el-button>
      <el-button v-if="enterpriseConfig.anchorSelectionAuthority == 1" :class="appType === 13 ? 'active' : ''"
        @click="changeAppType(13)">
        <div class="flex v-align-c">
          <img src="https://veekrayimg.joinsun.vip/images/zhubo.png" class="width-60 height-60 mar-r-18" />
          <span>主播小程序</span>
        </div>
      </el-button>
    </div>
    <div class="pad-l-20 pad-r-20 bg-color-white">
      <!-- <div class="div-style-2 mar-t-0">
        <p class="font-18">温馨提示：自定义页面需到店铺首页里做跳转关联否则无法在小程序前端直接进入。小程序最多只支持10级页面跳转，超过10级无法跳转。</p>
      </div> -->
      <div class="flex flex-between border-b height-80">
        <div class="top-operate">
          <el-button type="primary" @click="showCustomPage">+新建页面</el-button>
          <el-button type="primary" @click="goCusHotWordList">搜索页设置</el-button>
          <label>页面搜索：</label>
          <el-input style="width: 200px;" v-model="searchListQuery.pageTitle" placeholder="请输入内容"></el-input>
          <label v-if="this.storeOptions.length > 1 && appType === 10">首页类型：</label>
          <el-select v-if="this.storeOptions.length > 1 && appType === 10" v-model="defaultQuery.homeTypeList"
            placeholder="请选择" class="takeSelect">
            <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-button-group>
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
            <el-button plain="" @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <div class="tab-style-default">
        <el-tabs v-model="pageType" @tab-click="pageTypeClick">
          <el-tab-pane :label="labels['0']" name="0"> </el-tab-pane>
          <el-tab-pane :label="labels['10']" name="10"> </el-tab-pane>
          <el-tab-pane :label="labels['11']" name="11"> </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="customPageList" @selection-change="handleSelectionChange"
          v-loading="listLoading" element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header"
          row-class-name="default-row">
          <el-table-column label="页面名称">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <el-tag v-if="scope.row.homeFlag == 1 && scope.row.homeType == 1 " type="success">当前首页</el-tag>
                <el-tag v-else-if="scope.row.homeFlag == 1 && scope.row.homeType == 2 " type="danger">当前首页</el-tag>
                <el-tag v-else-if="scope.row.homeFlag == 1 && scope.row.homeType == 3 " type="warning">当前首页</el-tag>
                <el-tag v-else-if="scope.row.homeFlag == 1" type="success">当前首页</el-tag>
                <div v-if="scope.row.pageTitle" class="font-14 pad-l-6">
                  <div style="color:#155bd4;" @click="goPageDetail(scope.row, scope.row.pageType)">
                    {{scope.row.pageTitle}}
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="页面类型" :formatter="homeTypeFormat">
            <!--         <template slot-scope="scope" >
              <div>{{ dict.pageType[scope.row.pageType] }}</div>
            </template> -->
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime">
          </el-table-column>
          <el-table-column label="最后更新时间" prop="updateTime">
          </el-table-column>
          <el-table-column label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button v-if="appType === 10" type="text" size="medium"
                @click="copyHomeInfo(scope.row, scope.row.pageType)">
                复制
              </el-button>
              <el-button type="text" size="medium" @click="goPageDetail(scope.row, scope.row.pageType)">
                装修
              </el-button>
              <el-button type="text" size="medium" @click="publishCustomPage(scope.row)"
                v-if="scope.row.pageType == 10 && scope.row.homeFlag == 0">发布</el-button>
              <el-button type="text" size="medium" @click="delCustomPage(scope.row)" v-if="scope.row.homeFlag != 1">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 新建页面弹窗 -->
    <el-dialog title="选择创建类型" :visible.sync="dialogFormVisible" width="790px">
      <div class="page-content">
        <div class="flex-between pad-b-30">
          <div class="width-350 height-198 storehome">
            <div class="content-title">店铺首页</div>
            <div class="rightNew home" @click="showAddPage('10')">立即创建</div>
          </div>
          <div class="width-350 height-198 custompage">
            <div class="content-title">自定义页面</div>
            <div class="rightNew custom" @click="showAddPage('11')">立即创建</div>
          </div>
        </div>
        <div class="flex-between">
          <div class="width-230 height-180 three">
            <div class="content-title-1">商品详情</div>
            <div class="wait">敬请期待</div>
          </div>
          <div class="width-230 height-180 three">
            <div class="content-title-1">个人中心</div>
            <div class="wait">敬请期待</div>
          </div>
          <div class="width-230 height-180 three">
            <div class="content-title-1">通过模板创建</div>
            <div class="wait">敬请期待</div>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 编辑页面弹层 -->
    <el-dialog width="510px" v-el-drag-dialog title="新建页面" :visible.sync="addPageVisible" :close-on-press-escape="true">
      <el-form :model="customPage" :rules="rules" ref="customPage" label-position="right" label-width="100px"
        class="pad-l-25 pad-r-25">
        <el-form-item label="页面名称" prop="pageTitle" class="none-mar-b pad-b-10">
          <div class="mar-l-12 mar-r-12">
            <el-input style="width: 200px;" v-model="customPage.pageTitle" placeholder="最多10个字"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="页面类型" prop="pageType" class="none-mar-b pad-b-10">
          <div class="flex v-align-c font-12 pad-r-30 pad-l-16 pad-t-10">
            <el-radio v-model="customPage.pageType" :label="key" v-for="(val, key) in dict.pageType" :key="key">{{val}}
            </el-radio>
          </div>
        </el-form-item>
        <el-form-item v-if="this.storeOptions.length > 1 && appType === 10 && customPage.pageType === '10'" label="首页类型"
          prop="homeType" class="none-mar-b pad-b-10">
          <div class="flex v-align-c font-12 pad-r-30 pad-l-16 pad-t-10">
            <el-radio-group v-model="customPage.homeType">
              <el-radio :label="item.value" v-for="item in homeTypeList" :key="item.value">
                {{item.label}}
              </el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addPageVisible = false">取消</el-button>
        <el-button type="primary" @click="addCustomPage">确定</el-button>
      </div>
    </el-dialog>
    <!-- 复制页面弹层 -->
    <el-dialog width="510px" v-el-drag-dialog title="复制页面" :visible.sync="copyPageVisible"
      :close-on-press-escape="true">
      <el-form :rules="rules" ref="copyCustomPageFrom" :model="copyCustomPageFrom" label-position="right"
        label-width="100px" class="pad-l-25 pad-r-25">
        <el-form-item label="页面名称" prop="copyPageTitle" class="none-mar-b pad-b-10">
          <div class="mar-l-12 mar-r-12">
            <el-input style="width: 200px;" v-model="copyCustomPageFrom.copyPageTitle" placeholder="最多10个字"></el-input>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyPageVisible = false">取消</el-button>
        <el-button type="primary" @click="copyCustomPage">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="" :visible.sync="codeVisible" :close-on-press-escape="true" width="400px">
      <div>
        <img :src="shopHomeWxaCode" v-if="shopHomeWxaCode" style="width: 400px">
      </div>
      <div slot="footer" class="dialog-footer">
        <span>用微信“扫一扫”扫描上方二维码</span><br>
        <span>查看编辑效果</span>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    pageCustomPage,
    statPage,
    saveCustomPageOnly,
    publishCustomPage,
    deleteCustomPage,
    copyCustomPage
  } from '@/api/custom-page/page'
  import {
    getByEnterpriseId,
    doHomeWxaCode
  } from '@/api/user/enterprise'
  import elDragDialog from '@/directive/el-dragDialog'

  export default {
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        storeOptions: [],
        homeTypeList: [],
        newPageDialog: false,
        editPageVisible: false,
        dialogFormVisible: false,
        addPageVisible: false,
        copyPageVisible: false,
        total: 0,
        listLoading: true,
        pageType: '0',
        searchListQuery: {
          pageTitle: '',
          pageType: ''
        },
        defaultQuery: {
          enterpriseId: this.getEnterpriseId(),
          pageTitle: '',
          pageType: '',
          appType: 10,
          homeTypeList: '',
          currentPage: 1,
          size: 10
        },
        copyCustomPageFrom: {
          copyPageTitle: '',
          copyPageId: '',
          appType: ''
        },
        customPage: {
          pageTitle: '',
          appType: 10,
          pageType: '0',
          homeType: '0'
        },
        dict: {
          pageType: {}
        },
        customPageList: [],
        labels: {
          '0': '全部类型(0)',
          '10': '店铺首页(0)',
          '11': '自定义页(0)'
        },
        rules: {
          pageTitle: [{
            required: true,
            message: '请输入页面名称',
            trigger: 'blur'
          }, {
            max: 10,
            message: '最多10个字'
          }],
          copyPageTitle: [{
            required: true,
            message: '请输入页面名称',
            trigger: 'blur'
          }]
        },
        shopHomeWxaCode: '',
        codeVisible: false,
        appType: 10,
        // 企业配置信息
        enterpriseConfig: {
          shopSelectionAuthority: 0
        }
      }
    },
    // 初始化页面
    created() {
      this.searchListQuery = {
        ...this.defaultQuery
      }
      const type = this.getVersionType() * 1 === 5 ? 12 : this.appType
      // 已勾选_小B选品：若未配置云店小程序则无需提示报错
      if (this.enterpriseConfig.shopSelectionAuthority === 1) {
        doHomeWxaCode(this.getEnterpriseId(), type).then(response => {
          if (response.isError) return
          this.shopHomeWxaCode = response.data
        })
      }
      getByEnterpriseId(this.getEnterpriseId()).then(response => {
        if (response.isError) return
        this.enterpriseConfig = response.data
        if (this.enterpriseConfig.shopSelectionAuthority * 1 === 1 && this.enterpriseConfig.wholesaleAuthority *
          1 === 1) {
          // 开启小B选品，查询批发小程序装修列表
          this.appType = 11
        }
        if (this.getVersionType() * 1 === 5) {
          // 社区小程序
          this.appType = 12
        }
        var allLabelValue = ''
        var option = []
        allLabelValue = allLabelValue + '0,'
        if (this.enterpriseConfig.communityDistributionAuthority === 1) {
          var obj = {
            'value': '1',
            'label': '【分销】店铺首页'
          }
          allLabelValue = allLabelValue + '1,'
          option.push(obj)
          var homeTypeObj = {
            'value': '1',
            'label': '分销店铺'
          }
          this.homeTypeList.push(homeTypeObj)
        }
        if (this.enterpriseConfig.storeHomeAuthority === 1) {
          var obj1 = {
            'value': '2',
            'label': '【门店】店铺首页'
          }
          allLabelValue = allLabelValue + '2,'
          option.push(obj1)
          var homeTypeObj1 = {
            'value': '2',
            'label': '门店店铺'
          }
          this.homeTypeList.push(homeTypeObj1)
        }
        if (this.enterpriseConfig.groupBuyAuthority === 1) {
          var obj2 = {
            'value': '3',
            'label': '【团长】店铺首页'
          }
          allLabelValue = allLabelValue + '3,'
          option.push(obj2)
          var homeTypeObj2 = {
            'value': '3',
            'label': '团长店铺'
          }
          this.homeTypeList.push(homeTypeObj2)
        }
        if (option.length > 1) {
          var obj3 = {
            'value': allLabelValue.substring(0, allLabelValue.length - 1),
            'label': '全部'
          }
          option.unshift(obj3)
        }
        this.storeOptions = option
        if (this.storeOptions.length > 0) {
          this.defaultQuery.homeTypeList = this.storeOptions[0].value
        }
        // 先查询系统配置，再进行初始化
        this.init()
      })
    },
    mounted() {},
    methods: {
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.init()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.init()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      setSearchListQuery() {
        if (this.homeTypeList.length === 1) {
          this.defaultQuery.homeTypeList = '0,' + this.defaultQuery.homeTypeList
        }
        // 搜索状态
        this.searchListQuery = {
          enterpriseId: this.getEnterpriseId(),
          pageTitle: this.searchListQuery.pageTitle,
          pageType: this.pageType,
          appType: this.appType,
          currentPage: this.searchListQuery.currentPage,
          size: this.searchListQuery.size,
          homeTypeList: this.defaultQuery.homeTypeList
        }
        if (this.searchListQuery.pageType * 1 === 0) {
          this.searchListQuery.pageType = ''
        }
      },
      changeAppType(appType) {
        this.searchListQuery.currentPage = 1
        this.appType = appType
        this.init()
      },
      init() {
        if (this.homeTypeList.length > 0 || this.appType !== 10) {
          this.setSearchListQuery()
          statPage(this.searchListQuery).then(response => {
            if (response.isError) return
            this.labels['0'] = '全部类型(' + response.data['0'] + ')'
            this.labels['10'] = '店铺首页(' + response.data['10'] + ')'
            this.labels['11'] = '自定义页(' + response.data['11'] + ')'
          })
          pageCustomPage(this.searchListQuery).then(response => {
            if (response.isError) {
              return
            }
            this.total = response.data.total
            this.customPageList = response.data.records
            this.dict = response.data.dict
            this.listLoading = false
          })
        } else {
          this.labels['0'] = '全部类型(0)'
          this.labels['10'] = '店铺首页(0)'
          this.labels['11'] = '自定义页(0)'
          this.customPageList = null
          this.$message({
            type: 'error',
            message: '需至少开启【社群分销】【社区团购】【门店到家】等其中一个增值功能！'
          })
          this.listLoading = false
          return
        }
      },
      showAddPage(pageType) {
        if (this.homeTypeList.length > 0 || this.appType !== 10) {
          if (this.homeTypeList.length > 0) {
            this.customPage.homeType = this.homeTypeList[0].value
          }
          this.customPage.pageType = pageType
          this.customPage.appType = this.appType
          this.dialogFormVisible = false
          this.addPageVisible = true
        } else {
          this.$message({
            type: 'error',
            message: '需至少开启【社群分销】【社区团购】【门店到家】等其中一个增值功能！'
          })
          return
        }
      },
      pageTypeClick() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      showCustomPage() {
        this.dialogFormVisible = true
      },
      addCustomPage() {
        this.$refs.customPage.validate((valid) => {
          if (!valid) {
            return false
          }
          this.customPage.enterpriseId = this.getEnterpriseId()
          this.customPage.homeFlag = 0
          if (this.customPage.pageType === '11') {
            this.customPage.homeType = 0
          }
          saveCustomPageOnly(this.customPage).then(response => {
            if (response.isError) return
            this.$router.push({
              path: '/card/page-detail/index?pageId=' + response.data + '&pageType=' + this.customPage
                .pageType + '&appType=' + this.appType + '&homeType=' + this.customPage.homeType
            })
          })
        })
      },
      copyHomeInfo(row, type) {
        this.copyPageVisible = true
        this.copyCustomPageFrom.copyPageId = row.pageId
        this.copyCustomPageFrom.appType = row.appType
      },
      copyCustomPage() {
        this.$refs.copyCustomPageFrom.validate((valid) => {
          if (!valid) {
            return false
          }
          copyCustomPage(this.copyCustomPageFrom.copyPageId, this.copyCustomPageFrom.copyPageTitle, this
            .copyCustomPageFrom.appType).then(
            response => {
              if (response.isError) return
              this.copyPageVisible = false
              this.$message({
                type: 'success',
                message: '复制成功'
              })
              this.init()
            })
        })
      },
      goPageDetail(row, type) {
        this.$router.push({
          path: '/card/page-detail/index?pageId=' + row.pageId + '&pageType=' + type + '&appType=' + this.appType +
            '&homeType=' + row.homeType
        })
      },
      goCusHotWordList() {
        this.$router.push({
          path: '/card/page-detail/index?navType=13' + '&appType=' + this.appType
        })
      },
      publishCustomPage(row) {
        this.$confirm('是否确认将该页面替换到您当前小程序首页？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          publishCustomPage(this.getEnterpriseId(), row.pageId, row.appType, row.homeType).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '发布成功'
            })
            if (this.shopHomeWxaCode) {
              this.codeVisible = true
            }
            this.init()
          })
        })
      },
      delCustomPage(row) {
        this.$confirm('删除页面后将不可恢复，是否确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCustomPage(row.pageId).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.init()
          })
        })
      },
      homeTypeFormat(row, colomn) {
        var actions = []
        // 只有当店铺类型为10：店铺首页，且应用类型为10：云店小程序的时候才对首页进行判断
        if (row.pageType === 10 && row.appType === 10) {
          if (row.homeType === 1) {
            actions.push('【分销】店铺首页')
          } else if (row.homeType === 2) {
            actions.push('【门店】店铺首页')
          } else if (row.homeType === 3) {
            actions.push('【团长】店铺首页')
          } else {
            actions.push(this.dict.pageType[row.pageType])
          }
        } else {
          actions.push(this.dict.pageType[row.pageType])
        }

        return actions.join('')
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.init()
      },
      resetSearch() {
        if (this.storeOptions.length > 0) {
          this.defaultQuery.homeTypeList = this.storeOptions[0].value
        }
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.customPage = {
          pageType: '0',
          pageTitle: ''
        }
        this.init()
      }
    }
  }
</script>
<style lang="less" scoped>
  .tab-wx-type {
    .el-button {
      padding: 19px 95px 19px 17px;
      font-size: 19px;
      color: #323233;
      border-radius: 8px;
      box-shadow: 0px 2px 14px 0px rgba(154, 154, 154, 0.18);
      border: #fff 1px solid;

      &:hover,
      &.active {
        border: #4ba3ff 1px solid;
        background: #f8fbff;
      }

      img {
        border-radius: 50px;
      }
    }
  }

  .color-orange {
    color: #E6A23C;
  }

  .color-green {
    color: #67C23A;
  }

  .select-class {
    margin-right: -5px;
    width: 110px;
  }

  .mini-pic {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  // 新建页面弹窗
  .margin-container-list /deep/ .el-dialog__title {
    font-size: 24px;
    padding: 0 40px;
    color: #333333;
    font-weight: unset;
    text-align: left;
  }

  .margin-container-list /deep/ .el-dialog__headerbtn {
    font-size: 22px;
  }

  .top-operate {
    margin-bottom: 0;
    line-height: unset;

    label {
      font-weight: unset;
    }
  }

  .div-style-2 {
    height: 65px;
    line-height: 65px;
    padding: 0px 30px;
  }

  .page-content {
    padding: 0 30px 35px;
    line-height: 1;

    .storehome {
      background: url("../../../assets/images/new-page-1.png");
    }

    .custompage {
      background: url("../../../assets/images/new-page-2.png");
    }

    .three {
      background: url("../../../assets/images/new-page-3.png");
    }

    .flex-between {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .content-title {
      font-size: 30px;
      margin-left: 30px;
      padding-top: 35px;
      color: white;
    }

    .rightNew {
      margin-left: 30px;
      background: white;
      border-radius: 15px;
      width: 100px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      margin-top: 76px;
      font-size: 16px;
      cursor: pointer;
    }

    .content-title-1 {
      font-size: 30px;
      margin-left: 15px;
      padding-top: 32px;
      color: #A7A7A7;
    }

    .wait {
      margin-left: 15px;
      font-size: 16px;
      color: #A7A7A7;
      margin-top: 12px;
    }

    .home {
      color: #0DD2B9;
    }

    .custom {
      color: #48A3FF;
    }
  }

  .tab-style-default {
    /deep/ .el-tabs__header {
      margin: 0;
    }
  }
</style>
